<!DOCTYPE html>


<html lang="zh-CN">


<head>
  <meta charset="utf-8" />
  <meta name="baidu_union_verify" content="0423ec0cdca4f8eebe6e059172fc0e94">
  <meta name="baidu-site-verification" content="code-pR8Cu8CCAR" />
  <meta name="google-site-verification" content="kPx7uwBYN8ZNVw-1hPQgk5yziYYGu7ZawLlYvgTblwQ" />
  <meta name="sogou_site_verification" content="bt3Su26Lme"/>
  <meta name="360-site-verification" content="73ba99e99d3fc1e5f8a37d8c1d998703" />
   
  <meta name="keywords" content="LIEFox,liefox,liefox拾柒,LIEFox拾柒,编程笔记,JAVA,前端" />
   
  <meta name="description" content="LIEFox一个有趣又好玩的学习编程网站" />
  
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    Java泛型 |  LIEFox
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  
<script>
var _hmt = _hmt || [];
(function() {
	var hm = document.createElement("script");
	hm.src = "https://hm.baidu.com/hm.js?70837313b75a2b48b1e427bcabe5c0d9";
	var s = document.getElementsByTagName("script")[0]; 
	s.parentNode.insertBefore(hm, s);
})();
</script>



<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>

<!-- 封面标闪烁 -->
<link rel="stylesheet" href="/css/zhyBlogTitle.css">

<!-- Highlight.js -->
<link href="https://cdn.bootcdn.net/ajax/libs/highlight.js/9.18.1/styles/a11y-dark.min.css" rel="stylesheet">
<script src="https://cdn.bootcdn.net/ajax/libs/highlight.js/9.18.1/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>

</head>

</html>

<body>
  <div id="app">
    
      
      <canvas width="1777" height="841"
        style="position: fixed; left: 0px; top: 0px; z-index: 99999; pointer-events: none;"></canvas>
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-Java泛型"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  Java泛型
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/posts/a14eb637.html" class="article-date">
  <time datetime="2021-02-10T16:00:00.000Z" itemprop="datePublished">2021-02-11</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/JAVA%E7%AC%94%E8%AE%B0/">JAVA笔记</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">3.1k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">13 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <img src="https://i.loli.net/2021/02/11/i619e2TZCcMgoKk.png" alt="coding_ _2_.png" style="zoom:25%;" />

<a id="more"></a>

<h1 id="Java泛型"><a href="#Java泛型" class="headerlink" title="Java泛型"></a>Java泛型</h1><blockquote>
<p>泛型就是编写模板代码来适应任意类型；</p>
<p>泛型的好处是使用时不必对类型进行强制转换，它通过编译器对类型进行检查；</p>
<p>注意泛型的继承关系：可以把<code>ArrayList&lt;Integer&gt;</code>向上转型为<code>List&lt;Integer&gt;</code>（<code>T</code>不能变！），但不能把<code>ArrayList&lt;Integer&gt;</code>向上转型为<code>ArrayList&lt;Number&gt;</code>（<code>T</code>不能变成父类）。</p>
</blockquote>
<h2 id="使用泛型"><a href="#使用泛型" class="headerlink" title="使用泛型"></a>使用泛型</h2><p>当我们定义泛型类型<code>&lt;Number&gt;</code>后，<code>List&lt;T&gt;</code>的泛型接口变为强类型<code>List&lt;Number&gt;</code>：</p>
<figure class="highlight pgsql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">List&lt;Number&gt; list = <span class="built_in">new</span> ArrayList&lt;Number&gt;();</span><br><span class="line">list.<span class="keyword">add</span>(<span class="built_in">new</span> <span class="type">Integer</span>(<span class="number">123</span>));</span><br><span class="line">list.<span class="keyword">add</span>(<span class="built_in">new</span> <span class="type">Double</span>(<span class="number">12.34</span>));</span><br><span class="line">Number first = list.<span class="keyword">get</span>(<span class="number">0</span>);</span><br><span class="line">Number second = list.<span class="keyword">get</span>(<span class="number">1</span>);</span><br></pre></td></tr></table></figure>

<p>编译器如果能自动推断出泛型类型，就可以省略后面的泛型类型。例如，对于下面的代码：</p>
<figure class="highlight arcade"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">List&lt;<span class="built_in">Number</span>&gt; list = <span class="keyword">new</span> ArrayList&lt;<span class="built_in">Number</span>&gt;();</span><br></pre></td></tr></table></figure>

<p>编译器看到泛型类型<code>List&lt;Number&gt;</code>就可以自动推断出后面的<code>ArrayList&lt;T&gt;</code>的泛型类型必须是<code>ArrayList&lt;Number&gt;</code>，因此，可以把代码简写为：</p>
<figure class="highlight arcade"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 可以省略后面的Number，编译器可以自动推断泛型类型：</span></span><br><span class="line">List&lt;<span class="built_in">Number</span>&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br></pre></td></tr></table></figure>

<h3 id="泛型接口"><a href="#泛型接口" class="headerlink" title="泛型接口"></a>泛型接口</h3><p>除了<code>ArrayList&lt;T&gt;</code>使用了泛型，还可以在接口中使用泛型。例如，<code>Arrays.sort(Object[])</code>可以对任意数组进行排序，但待排序的元素必须实现<code>Comparable&lt;T&gt;</code>这个泛型接口：</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="symbol">Comparable</span>&lt;<span class="symbol">T</span>&gt; &#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 返回负数: 当前实例比参数o小</span></span><br><span class="line"><span class="comment">     * 返回0: 当前实例与参数o相等</span></span><br><span class="line"><span class="comment">     * 返回正数: 当前实例比参数o大</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="built_in">int</span> compareTo(T o);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以直接对<code>String</code>数组进行排序:</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Main</span> &#123;</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(<span class="keyword">String</span>[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">String</span>[] strings = &#123;<span class="string">&quot;apple&quot;</span>, <span class="string">&quot;watch&quot;</span>, <span class="string">&quot;book&quot;</span>&#125;;</span><br><span class="line">        Arrays.sort(strings);</span><br><span class="line">        System.out.<span class="built_in">println</span>(Arrays.toString(strings));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>使用泛型时，把泛型参数<code>&lt;T&gt;</code>替换为需要的class类型，例如：<code>ArrayList&lt;String&gt;</code>，<code>ArrayList&lt;Number&gt;</code>等；</p>
<p>可以省略编译器能自动推断出的类型，例如：<code>List&lt;String&gt; list = new ArrayList&lt;&gt;();</code>；</p>
<p>不指定泛型参数类型时，编译器会给出警告，且只能将<code>&lt;T&gt;</code>视为<code>Object</code>类型；</p>
<p>可以在接口中定义泛型类型，实现此接口的类必须实现正确的泛型类型。</p>
<h2 id="编写泛型"><a href="#编写泛型" class="headerlink" title="编写泛型"></a>编写泛型</h2><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Pair</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> T first;</span><br><span class="line">    <span class="keyword">private</span> T last;</span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="title">Pair</span>(<span class="params">T first, T last</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.first = first;</span><br><span class="line">        <span class="built_in">this</span>.last = last;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> T <span class="function"><span class="title">getFirst</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> first;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> T <span class="function"><span class="title">getLast</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> last;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="静态方法"><a href="#静态方法" class="headerlink" title="静态方法"></a>静态方法</h3><p>编写泛型类时，要特别注意，泛型类型<code>&lt;T&gt;</code>不能用于静态方法。例如：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Pair</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> T first;</span><br><span class="line">    <span class="keyword">private</span> T last;</span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="title">Pair</span>(<span class="params">T first, T last</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.first = first;</span><br><span class="line">        <span class="built_in">this</span>.last = last;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> T <span class="function"><span class="title">getFirst</span>(<span class="params"></span>)</span> &#123; ... &#125;</span><br><span class="line">    <span class="keyword">public</span> T <span class="function"><span class="title">getLast</span>(<span class="params"></span>)</span> &#123; ... &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 对静态方法使用&lt;T&gt;:</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Pair&lt;T&gt; <span class="function"><span class="title">create</span>(<span class="params">T first, T last</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Pair&lt;T&gt;(first, last);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上述代码会导致编译错误，我们无法在静态方法<code>create()</code>的方法参数和返回类型上使用泛型类型<code>T</code>。</p>
<p>有些同学在网上搜索发现，可以在<code>static</code>修饰符后面加一个<code>&lt;T&gt;</code>，编译就能通过：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Pair</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> T first;</span><br><span class="line">    <span class="keyword">private</span> T last;</span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="title">Pair</span>(<span class="params">T first, T last</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.first = first;</span><br><span class="line">        <span class="built_in">this</span>.last = last;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> T <span class="function"><span class="title">getFirst</span>(<span class="params"></span>)</span> &#123; ... &#125;</span><br><span class="line">    <span class="keyword">public</span> T <span class="function"><span class="title">getLast</span>(<span class="params"></span>)</span> &#123; ... &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 可以编译通过:</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; Pair&lt;T&gt; <span class="function"><span class="title">create</span>(<span class="params">T first, T last</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Pair&lt;T&gt;(first, last);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>但实际上，这个<code>&lt;T&gt;</code>和<code>Pair&lt;T&gt;</code>类型的<code>&lt;T&gt;</code>已经没有任何关系了。</p>
<p>对于静态方法，我们可以单独改写为“泛型”方法，只需要使用另一个类型即可。对于上面的<code>create()</code>静态方法，我们应该把它改为另一种泛型类型，例如，<code>&lt;K&gt;</code>：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Pair</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> T first;</span><br><span class="line">    <span class="keyword">private</span> T last;</span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="title">Pair</span>(<span class="params">T first, T last</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.first = first;</span><br><span class="line">        <span class="built_in">this</span>.last = last;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> T <span class="function"><span class="title">getFirst</span>(<span class="params"></span>)</span> &#123; ... &#125;</span><br><span class="line">    <span class="keyword">public</span> T <span class="function"><span class="title">getLast</span>(<span class="params"></span>)</span> &#123; ... &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 静态泛型方法应该使用其他类型区分:</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;K&gt; Pair&lt;K&gt; <span class="function"><span class="title">create</span>(<span class="params">K first, K last</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Pair&lt;K&gt;(first, last);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这样才能清楚地将静态方法的泛型类型和实例类型的泛型类型区分开。</p>
<h3 id="多个泛型类型"><a href="#多个泛型类型" class="headerlink" title="多个泛型类型"></a>多个泛型类型</h3><p>泛型还可以定义多种类型。例如，我们希望<code>Pair</code>不总是存储两个类型一样的对象，就可以使用类型<code>&lt;T, K&gt;</code>：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Pair</span>&lt;<span class="title">T</span>, <span class="title">K</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> T first;</span><br><span class="line">    <span class="keyword">private</span> K last;</span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="title">Pair</span>(<span class="params">T first, K last</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.first = first;</span><br><span class="line">        <span class="built_in">this</span>.last = last;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> T <span class="function"><span class="title">getFirst</span>(<span class="params"></span>)</span> &#123; ... &#125;</span><br><span class="line">    <span class="keyword">public</span> K <span class="function"><span class="title">getLast</span>(<span class="params"></span>)</span> &#123; ... &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>使用的时候，需要指出两种类型：</p>
<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Pair</span>&lt;<span class="built_in">String</span>, <span class="built_in">Integer</span>&gt; p = <span class="literal">new</span> <span class="built_in">Pair</span>&lt;&gt;(<span class="string">&quot;test&quot;</span>, <span class="number">123</span>);</span><br></pre></td></tr></table></figure>

<p>Java标准库的<code>Map&lt;K, V&gt;</code>就是使用两种泛型类型的例子。它对Key使用一种类型，对Value使用另一种类型。</p>
<blockquote>
<p>编写泛型时，需要定义泛型类型<code>&lt;T&gt;</code>；</p>
<p>静态方法不能引用泛型类型<code>&lt;T&gt;</code>，必须定义其他类型（例如<code>&lt;K&gt;</code>）来实现静态泛型方法；</p>
<p>泛型可以同时定义多种类型，例如<code>Map&lt;K, V&gt;</code>。</p>
</blockquote>
<h2 id="类型擦拭"><a href="#类型擦拭" class="headerlink" title="类型擦拭"></a>类型擦拭</h2><p>泛型是一种类似”模板代码“的技术，不同语言的泛型实现方式不一定相同。</p>
<p>Java语言的泛型实现方式是擦拭法（Type Erasure）。</p>
<p>所谓擦拭法是指，虚拟机对泛型其实一无所知，所有的工作都是编译器做的。</p>
<p>例如，我们编写了一个泛型类<code>Pair&lt;T&gt;</code>，这是编译器看到的代码：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Pair</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> T first;</span><br><span class="line">    <span class="keyword">private</span> T last;</span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="title">Pair</span>(<span class="params">T first, T last</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.first = first;</span><br><span class="line">        <span class="built_in">this</span>.last = last;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> T <span class="function"><span class="title">getFirst</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> first;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> T <span class="function"><span class="title">getLast</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> last;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>而虚拟机根本不知道泛型。这是虚拟机执行的代码：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Pair</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="built_in">Object</span> first;</span><br><span class="line">    <span class="keyword">private</span> <span class="built_in">Object</span> last;</span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="title">Pair</span>(<span class="params"><span class="built_in">Object</span> first, <span class="built_in">Object</span> last</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.first = first;</span><br><span class="line">        <span class="built_in">this</span>.last = last;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="built_in">Object</span> <span class="function"><span class="title">getFirst</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> first;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="built_in">Object</span> <span class="function"><span class="title">getLast</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> last;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>因此，Java使用擦拭法实现泛型，导致了：</p>
<ul>
<li>编译器把类型<code>&lt;T&gt;</code>视为<code>Object</code>；</li>
<li>编译器根据<code>&lt;T&gt;</code>实现安全的强制转型。</li>
</ul>
<p>擦拭法决定了泛型<code>&lt;T&gt;</code>：</p>
<ul>
<li>不能是基本类型，例如：<code>int</code>；</li>
<li>不能获取带泛型类型的<code>Class</code>，例如：<code>Pair&lt;String&gt;.class</code>；</li>
<li>不能判断带泛型类型的类型，例如：<code>x instanceof Pair&lt;String&gt;</code>；</li>
<li>不能实例化<code>T</code>类型，例如：<code>new T()</code>。</li>
</ul>
<p>泛型方法要防止重复定义方法，例如：<code>public boolean equals(T obj)</code>；</p>
<p>子类可以获取父类的泛型类型<code>&lt;T&gt;</code>。</p>
<h2 id="上限通配符"><a href="#上限通配符" class="headerlink" title="上限通配符"></a>上限通配符</h2><p><code>&lt;? extends T&gt;</code>上限通配，表示？是T的一个未知子类。</p>
<p>举个例子<br>我们有一个水果类</p>
<figure class="highlight axapta"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 水果类</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">Fruit</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> eat();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后创建两种水果继承水果类Fruit</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 苹果类</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">Apple</span> <span class="keyword">extends</span> <span class="title">Fruit</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    public void eat() &#123;</span><br><span class="line">        <span class="type">System</span>.out.println(<span class="string">&quot;我是苹果，我是酸酸甜甜的&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 香蕉类</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">Banana</span> <span class="keyword">extends</span> <span class="title">Fruit</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    public void eat() &#123;</span><br><span class="line">        <span class="type">System</span>.out.println(<span class="string">&quot;我是香蕉，我是软软的&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们还需要一个吃瓜群众</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 吃瓜群众</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">People&lt;T</span> <span class="keyword">extends</span>  <span class="title">Fruit&gt;</span> </span>&#123;</span><br><span class="line">    public void eatFruit(<span class="type">T</span> t)&#123;</span><br><span class="line">        t.eat();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>请注意定义People类的时候我们使用了泛型上限表示<code>&lt;T extends Fruit&gt;</code><br>我们创建一个类测试一下</p>
<figure class="highlight haxe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> void main(<span class="keyword">String</span>[] args) &#123;</span><br><span class="line">        People&lt;Apple&gt; p1 = <span class="keyword">new</span> <span class="type">People</span>&lt;&gt;();</span><br><span class="line">        p1.eatFruit(<span class="keyword">new</span> <span class="type">Apple</span>());</span><br><span class="line">         </span><br><span class="line">        People&lt;Banana&gt; p2 = <span class="keyword">new</span> <span class="type">People</span>&lt;&gt;();</span><br><span class="line">        p2.eatFruit(<span class="keyword">new</span> <span class="type">Banana</span>());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//结果：我是苹果，我是酸酸甜甜的</span></span><br><span class="line">		我是香蕉，我是软软的</span><br></pre></td></tr></table></figure>

<p>若此时我们创建一个橙子类，但不继承自Fruit父类</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 橙子类</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Orange</span> &#123;</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">eat</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.<span class="built_in">println</span>(<span class="string">&quot;我是橙子，我是酸酸的&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>编译时期就会报错，提示Orange不在范围内，应该要继承Fruit类</p>
<p>编译报错</p>
<img src="https://i.loli.net/2021/02/24/5kxLBdRrHXZn9MQ.png" alt="image.png"  />

<p>表示只能接收Number这个类以及这个类的子类的数据类型。（extends表继承，就是这个类下面的东西）再举个例子如下</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public <span class="keyword">static</span> <span class="keyword">void</span> <span class="function"><span class="keyword">function</span>(<span class="params">Student&lt;? <span class="keyword">extends</span> <span class="built_in">Number</span>&gt; s</span>)</span>&#123; </span><br><span class="line">    System.out.println(<span class="string">&quot;姓名是：&quot;</span>+s.getName()); </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="下限通配符"><a href="#下限通配符" class="headerlink" title="下限通配符"></a>下限通配符</h2><p><code>&lt;? super T&gt;</code>下限通配，表示？是T的一个未知父类。</p>
<p>这里？表示一个未知的类，而T是一个具体的类，在实际使用的时候T需要替换成一个具体的类，表示实例化的时候泛型参数要是T的父类。</p>
<p>例如</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="built_in">void</span> <span class="function"><span class="title">addNumbers</span>(<span class="params">List&lt;? <span class="built_in">super</span> Integer&gt; list</span>)</span> &#123;</span><br><span class="line">    <span class="keyword">for</span> (int i = <span class="number">1</span>; i &lt;= <span class="number">10</span>; i++) &#123;</span><br><span class="line">        list.add(i);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里表示我们调用这个方法时可以传入参数是Integer或者Integer的父类，例如：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestLowerBounded</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="built_in">void</span> <span class="function"><span class="title">addNumbers</span>(<span class="params">List&lt;? <span class="built_in">super</span> Integer&gt; list</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">for</span> (int i = <span class="number">1</span>; i &lt;= <span class="number">10</span>; i++) &#123;</span><br><span class="line">            list.add(i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="built_in">void</span> <span class="function"><span class="title">main</span>(<span class="params"><span class="built_in">String</span>[] args</span>)</span> &#123;</span><br><span class="line">        List&lt;Integer&gt; list1 = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        addNumbers(list1);</span><br><span class="line"> </span><br><span class="line">        List&lt;<span class="built_in">Number</span>&gt; list2 = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        addNumbers(list2);</span><br><span class="line"> </span><br><span class="line">        List&lt;<span class="built_in">Object</span>&gt; list3 = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        addNumbers(list3);</span><br><span class="line"> </span><br><span class="line">        List&lt;<span class="built_in">String</span>&gt; list4 = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        <span class="comment">//编译错误，因为String不是Integer的父类</span></span><br><span class="line">        <span class="comment">//addNumbers(list4);</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Number和Object都是Integer的父类，所以编译通过，而String不是Integer的父类，编译报错。</p>
<p>表示只能接收Number这个类以及这个类的父类的数据类型。（super表父类，超过这个类的东西）再举个例子如下</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public <span class="keyword">static</span> <span class="keyword">void</span> <span class="function"><span class="keyword">function</span>(<span class="params">Student&lt;? <span class="built_in">super</span> <span class="built_in">Number</span>&gt; s</span>)</span>&#123; </span><br><span class="line">    System.out.println(<span class="string">&quot;姓名是：&quot;</span>+s.getName()); </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="泛型和反射"><a href="#泛型和反射" class="headerlink" title="泛型和反射"></a>泛型和反射</h2><p>Java的部分反射API也是泛型。例如：<code>Class&lt;T&gt;</code>就是泛型：</p>
<figure class="highlight delphi"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// compile warning:</span></span><br><span class="line"><span class="keyword">Class</span> clazz = <span class="keyword">String</span>.<span class="keyword">class</span>;</span><br><span class="line"><span class="keyword">String</span> str = (<span class="keyword">String</span>) clazz.newInstance();</span><br><span class="line"></span><br><span class="line"><span class="comment">// no warning:</span></span><br><span class="line"><span class="keyword">Class</span>&lt;<span class="keyword">String</span>&gt; clazz = <span class="keyword">String</span>.<span class="keyword">class</span>;</span><br><span class="line"><span class="keyword">String</span> str = clazz.newInstance();</span><br></pre></td></tr></table></figure>

<p>调用<code>Class</code>的<code>getSuperclass()</code>方法返回的<code>Class</code>类型是<code>Class&lt;? super T&gt;</code>：</p>
<figure class="highlight coffeescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Class&lt;? <span class="built_in">super</span> <span class="built_in">String</span>&gt; sup = <span class="built_in">String</span>.<span class="keyword">class</span>.getSuperclass();</span><br></pre></td></tr></table></figure>

<p>构造方法<code>Constructor&lt;T&gt;</code>也是泛型：</p>
<figure class="highlight delphi"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">Class</span>&lt;Integer&gt; clazz = Integer.<span class="keyword">class</span>;</span><br><span class="line"><span class="function"><span class="keyword">Constructor</span>&lt;<span class="title">Integer</span>&gt; <span class="title">cons</span> = <span class="title">clazz</span>.<span class="title">getConstructor</span><span class="params">(int.<span class="keyword">class</span>)</span>;</span></span><br><span class="line">Integer i = cons.newInstance(<span class="number">123</span>);</span><br></pre></td></tr></table></figure>

<p>我们可以声明带泛型的数组，但不能用<code>new</code>操作符创建带泛型的数组：</p>
<figure class="highlight haxe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Pair&lt;<span class="keyword">String</span>&gt;[] ps = <span class="literal">null</span>; <span class="comment">// ok</span></span><br><span class="line">Pair&lt;<span class="keyword">String</span>&gt;[] ps = <span class="keyword">new</span> <span class="type">Pair</span>&lt;<span class="keyword">String</span>&gt;[<span class="number">2</span>]; <span class="comment">// compile error!</span></span><br></pre></td></tr></table></figure>

<p>必须通过强制转型实现带泛型的数组：</p>
<figure class="highlight julia"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SuppressWarnings</span>(<span class="string">&quot;unchecked&quot;</span>)</span><br><span class="line"><span class="built_in">Pair</span>&lt;<span class="built_in">String</span>&gt;[] ps = (<span class="built_in">Pair</span>&lt;<span class="built_in">String</span>&gt;[]) new <span class="built_in">Pair</span>[<span class="number">2</span>];</span><br></pre></td></tr></table></figure>

<p>使用泛型数组要特别小心，因为数组实际上在运行期没有泛型，编译器可以强制检查变量<code>ps</code>，因为它的类型是泛型数组。但是，编译器不会检查变量<code>arr</code>，因为它不是泛型数组。因为这两个变量实际上指向同一个数组，所以，操作<code>arr</code>可能导致从<code>ps</code>获取元素时报错，例如，以下代码演示了不安全地使用带泛型的数组：</p>
<figure class="highlight julia"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Pair</span>[] arr = new <span class="built_in">Pair</span>[<span class="number">2</span>];</span><br><span class="line"><span class="built_in">Pair</span>&lt;<span class="built_in">String</span>&gt;[] ps = (<span class="built_in">Pair</span>&lt;<span class="built_in">String</span>&gt;[]) arr;</span><br><span class="line"></span><br><span class="line">ps[<span class="number">0</span>] = new <span class="built_in">Pair</span>&lt;<span class="built_in">String</span>&gt;(<span class="string">&quot;a&quot;</span>, <span class="string">&quot;b&quot;</span>);</span><br><span class="line">arr[<span class="number">1</span>] = new <span class="built_in">Pair</span>&lt;<span class="built_in">Integer</span>&gt;(<span class="number">1</span>, <span class="number">2</span>);</span><br><span class="line"></span><br><span class="line">// ClassCastException:</span><br><span class="line"><span class="built_in">Pair</span>&lt;<span class="built_in">String</span>&gt; p = ps[<span class="number">1</span>];</span><br><span class="line"><span class="built_in">String</span> s = p.getFirst();</span><br></pre></td></tr></table></figure>

<p>要安全地使用泛型数组，必须扔掉<code>arr</code>的引用：</p>
<figure class="highlight julia"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SuppressWarnings</span>(<span class="string">&quot;unchecked&quot;</span>)</span><br><span class="line"><span class="built_in">Pair</span>&lt;<span class="built_in">String</span>&gt;[] ps = (<span class="built_in">Pair</span>&lt;<span class="built_in">String</span>&gt;[]) new <span class="built_in">Pair</span>[<span class="number">2</span>];</span><br></pre></td></tr></table></figure>

<p>上面的代码中，由于拿不到原始数组的引用，就只能对泛型数组<code>ps</code>进行操作，这种操作就是安全的。</p>
<p>带泛型的数组实际上是编译器的类型擦除：</p>
<figure class="highlight julia"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Pair</span>[] arr = new <span class="built_in">Pair</span>[<span class="number">2</span>];</span><br><span class="line"><span class="built_in">Pair</span>&lt;<span class="built_in">String</span>&gt;[] ps = (<span class="built_in">Pair</span>&lt;<span class="built_in">String</span>&gt;[]) arr;</span><br><span class="line"></span><br><span class="line">System.out.println(ps.getClass() == <span class="built_in">Pair</span>[].class); // <span class="literal">true</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">String</span> s1 = (<span class="built_in">String</span>) arr[<span class="number">0</span>].getFirst();</span><br><span class="line"><span class="built_in">String</span> s2 = ps[<span class="number">0</span>].getFirst();</span><br></pre></td></tr></table></figure>

<p>所以我们不能直接创建泛型数组<code>T[]</code>，因为擦拭后代码变为<code>Object[]</code>：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// compile error:</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Abc</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    T[] <span class="function"><span class="title">createArray</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> T[<span class="number">5</span>];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>必须借助<code>Class&lt;T&gt;</code>来创建泛型数组：</p>
<figure class="highlight reasonml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">T<span class="literal">[]</span> create<span class="constructor">Array(Class&lt;T&gt; <span class="params">cls</span>)</span> &#123;</span><br><span class="line">    return (T<span class="literal">[]</span>) <span class="module-access"><span class="module"><span class="identifier">Array</span>.</span></span><span class="keyword">new</span><span class="constructor">Instance(<span class="params">cls</span>, 5)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们还可以利用可变参数创建泛型数组<code>T[]</code>：</p>
<figure class="highlight reasonml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">public <span class="keyword">class</span> ArrayHelper &#123;</span><br><span class="line">    @SafeVarargs</span><br><span class="line">    static &lt;T&gt; T<span class="literal">[]</span> <span class="keyword">as</span><span class="constructor">Array(T<span class="operator">...</span> <span class="params">objs</span>)</span> &#123;</span><br><span class="line">        return objs;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">String<span class="literal">[]</span> ss = <span class="module-access"><span class="module"><span class="identifier">ArrayHelper</span>.</span></span><span class="keyword">as</span><span class="constructor">Array(<span class="string">&quot;a&quot;</span>, <span class="string">&quot;b&quot;</span>, <span class="string">&quot;c&quot;</span>)</span>;</span><br><span class="line">Integer<span class="literal">[]</span> ns = <span class="module-access"><span class="module"><span class="identifier">ArrayHelper</span>.</span></span><span class="keyword">as</span><span class="constructor">Array(1, 2, 3)</span>;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>部分反射API是泛型，例如：<code>Class&lt;T&gt;</code>，<code>Constructor&lt;T&gt;</code>；</p>
<p>可以声明带泛型的数组，但不能直接创建带泛型的数组，必须强制转型；</p>
<p>可以通过<code>Array.newInstance(Class&lt;T&gt;, int)</code>创建<code>T[]</code>数组，需要强制转型；</p>
<p>同时使用泛型和可变参数时需要特别小心。</p>
</blockquote>
<p>作者：zjh</p>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          打赏
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本网站所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=https://cxq21.gitee.io/posts/a14eb637.html" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/JAVA%E7%AC%94%E8%AE%B0/" rel="tag">JAVA笔记</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/posts/c51233f6.html" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            JavaIO流
          
        </div>
      </a>
    
    
      <a href="/posts/adc18de0.html" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">Java反射</div>
      </a>
    
  </nav>

  
      
<!-- minivaline评论 -->
<div id="mvcomments-box">
  <div id="mvcomments"></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/minivaline@3/dist/MiniValine.min.js"></script>
<script>
    new MiniValine({
        el: '#mvcomments',
        appId: 'lGCocPMCSUz2tL4FcKDvFCG3-gzGzoHsz',
        appKey: 'VheJztjyMzs24xKQPGGI1bmh',
        mode: 'xCss',
        placeholder: '评论的时候建议填上您的邮箱，可以第一时间收到我的回复喔',
        pathname: window.location.pathname,
        lang: '',
        adminEmailMd5: '69b690b67d0fb9dba8ab2de5db6dd353',
        tagMeta: ["LIEFox站长", "小伙伴", "来将可留姓名"],
        master: ["69b690b67d0fb9dba8ab2de5db6dd353"],
        friends: ["1f7c8b18fb7bbe18fbaf97309de2c0ac", "e5aec373ad8a0dce7abdbe4e6585a8ba"],
        math: true,
        md: true,
        enableQQ: true,
        NoRecordIP: true,
        visitor: false,
        maxNest: 6,
        pageSize: 6,
        serverURLs: '',
        emoticonUrl: ["https://cdn.jsdelivr.net/npm/alus@latest", "https://cdn.jsdelivr.net/gh/MiniValine/qq@latest", "https://cdn.jsdelivr.net/gh/MiniValine/Bilibilis@latest", "https://cdn.jsdelivr.net/gh/MiniValine/tieba@latest", "https://cdn.jsdelivr.net/gh/MiniValine/twemoji@latest", "https://cdn.jsdelivr.net/gh/MiniValine/weibo@latest"],
    });
  const infoEle = document.querySelector('#mvcomments .info');
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
      infoEle.childNodes.forEach(function (item) {
          item.parentNode.removeChild(item);
      });
  }
</script>
<style>
	#mvcomments-box {
	padding: 5px 30px;
	}

	@media screen and (max-width: 800px) {
	#mvcomments-box {
	  padding: 5px 0px;
	}
	}

	.v .vlist .vcard .vh {
	padding-right: 20px;
	}

	.v .vlist .vcard {
	padding-left: 10px;
	}
	
	.darkmode .commentTrigger{
		background-color: #403e3e !important;
	  }
	.darkmode .MiniValine .vpage .more{
		background: #21232F
	}
	.darkmode img{
		  filter: brightness(30%)
	}
	.darkmode .MiniValine .vlist .vcard .vcomment-body .text-wrapper .vcomment.expand:before{
		background: linear-gradient(180deg, rgba(246,246,246,0), rgba(0,0,0,0.9))
	}
	.darkmode .MiniValine .vlist .vcard .vcomment-body .text-wrapper .vcomment.expand:after{
		background: rgba(0,0,0,0.9)
	}
	.darkmode .MiniValine .vlist .vcard .vcomment-body .text-wrapper .vcomment pre{
		background: #282c34
		border: 1px solid #282c34
	}
	.darkmode .MiniValine .vinputs-area .textarea-wrapper textarea{
		color: #000;
	}
	.darkmode .MiniValine .vinputs-area .auth-section .input-wrapper input{
		color: #000;
	}
	.darkmode .MiniValine .info .col .count{
		color: #000;
	}
	.darkmode .MiniValine .vinputs-area .vextra-area .vsmile-icons{
		background: transparent;
	}
</style>

 
</article>

</section>
      <footer class="footer">
  <div class="outer">
<!-- 运行天数 -->
    <ul>
        <li><span id="runtime_span"></span></li>
    </ul>

<script type="text/javascript">            
    function show_runtime() {
        window.setTimeout("show_runtime()", 1000);
        X = new Date("11/27/2020 17:17:17");
        Y = new Date();
        T = (Y.getTime() - X.getTime());
        M = 24 * 60 * 60 * 1000;
        a = T / M;
        A = Math.floor(a);
        b = (a - A) * 24;
        B = Math.floor(b);
        c = (b - B) * 60;
        C = Math.floor((b - B) * 60);
        D = Math.floor((c - C) * 60);
        runtime_span.innerHTML = "LIEFox逃脱猎人的第" + A + "天" + B + "小时" + C + "分" + D + "秒"
    }
    show_runtime();
</script>

    <ul>
      <li>
        Copyrights &copy;
        2020-2023
        <i class="ri-heart-fill heart_icon"></i> 拾柒工作室
      </li>
    </ul>


    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1279472270&amp;web_id=1279472270'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/LIEFox.png" alt="LIEFox"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">时间线</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友链</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/dplayer">视频</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/update">更新日志</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about">关于LIEFox</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="搜索">
        <i class="ri-search-line"></i>
      </a>
      
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>感谢金主~</p>
  <div class="reward-box">
    
    
    <div class="reward-item">
      <img class="reward-img" src="/images/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->


<script src="/js/clickBoom2.js"></script>


<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


<script src="/js/dz.js"></script>



    
  </div>
</body>

</html>